package com.herohead;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;

public class Rabbitmq {

	public String hostName;
	public String queue;
	public ConnectionFactory factory = new ConnectionFactory();
	public Channel channel;
	public QueueingConsumer consumer;
	public QueueingConsumer.Delivery delivery;
	public boolean autoAck = true;
	private String hostname;

	public void comsumerStart() throws IOException {
		consumer = new QueueingConsumer(channel);
		channel.basicConsume(queue, autoAck, consumer);
	}

	public void declareQue() throws IOException {
		//Channel channel = connection.createChannel();
		channel.queueDeclare(queue, false, false, false, null);
	}

	public void declareQueDurable() throws IOException {
		//Channel channel = connection.createChannel();
		channel.queueDeclare(queue, true, false, false, null);
	}

	public Channel getChannel() {
		return channel;
	}
	public String getHostname() {
		return factory.getHost();
	}
	public String getmessage() throws ShutdownSignalException, RuntimeException, InterruptedException {

		QueueingConsumer.Delivery delivery = consumer.nextDelivery();
		String message = new String(delivery.getBody());
		return message;
	}
	public String getQueue() {
		return queue;
	}
	public void setHostname(String strHostname) {
		factory.setHost(strHostname);
		hostname = strHostname;
	}
	public void setLogin (String vHost, String vPassword, String vUsername) {
		factory.setVirtualHost(vHost);
		factory.setPassword(vPassword);
		factory.setUsername(vUsername);
		//factory.setPort(888);
	}
	public void setQueue(String strQueue) {
		queue = strQueue;
	}

	public Channel setupChannel() throws IOException {

		final int numberOfRetries = 10 ;
		final long timeToWait = 30000 ;

		Connection connection = null;

		for (int i=1; i<numberOfRetries; i++) {

			try {

				connection = factory.newConnection();
				break ;
			}
			catch (Exception e) {
				try {
					System. out .println("Trying to connect to " + hostname + " - try " + i + " of " + numberOfRetries + " - retry in 30 secs" );
					Thread. sleep(timeToWait);
				}
				catch (InterruptedException e1) {
				}
			}
		}

		channel = connection.createChannel();
		return channel;
	}
}



